package com.luxsoft.siipap.em.replica.ui.tasks;

import java.util.List;

import javax.swing.SwingWorker;

import org.apache.log4j.Appender;
import org.apache.log4j.Logger;

import com.luxsoft.siipap.model.core.Cliente;
import com.luxsoft.siipap.service.ServiceLocator2;
import com.luxsoft.siipap.util.DBUtils;

/**
 * Componente grafico para la actualizacion de clientes de credito
 * 
 * @author Ruben Cancino
 *
 */
public class ExportadorDeSaldosDeClientesTask {

	public ExportadorDeSaldosDeClientesTask() {	}
	
	private Logger logger=Logger.getLogger(getClass());
	
	public void execute(){
		TaskDialog dialog=new TaskDialog("Exportar saldo de clientes de credito");
		final SwingWorker worker=new Importador(dialog);
		dialog.registerWorker(worker);		
		Appender appender=dialog.registerDetailLogHandler(logger);
		dialog.open();
		logger.removeAppender(appender);		
	}
	
	private class Importador extends SwingWorker<String,String>{
		
		private final TaskDialog dialog;
		
		
		public Importador(final TaskDialog dialog){
			this.dialog=dialog;
		}

		@Override
		protected String doInBackground() throws Exception {
			List<Cliente> clientes=ServiceLocator2.getHibernateTemplate().find("from Cliente c left join fetch c.credito where c.credito is not null order by c.clave desc");
			publish("Preparando clientes");
			int total=clientes.size();
			int i=1;
			for(Cliente c:clientes){
				publish("Procesando cliente:"+c);
				try {
					String res=ServiceLocator2.getClienteServices().exportarSaldo(c);					
					logger.info("Exportando:" +res);
				} catch (Exception e) {
					logger.error(e);
					continue;
				}finally{
					i++;
					setProgress(i*100/total);
				}
			}
			return "OK";
		}

		@Override
		protected void process(List<String> chunks) {
			for(String s:chunks){
				dialog.getHeader().setDescription(s);
			}
		}
		
	}
	
	public static void main(String[] args) {
		DBUtils.whereWeAre();
		new ExportadorDeSaldosDeClientesTask().execute();
	}

}
